package com.example.study.basic.handler;

import com.example.study.basic.exception.BasicCode;
import com.example.study.basic.exception.BasicException;
import com.example.study.basic.model.ResultModel;
import com.example.study.basic.util.LoggerUtil;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @author: nannan
 * @date: 2020/9/10 10:41 下午
 * @description: 全局异常处理器
 */
@RestControllerAdvice
public class MyExceptionHandler {

    /**
     * @description: 捕获未知异常
     * @author: nannan
     * @date: 2020/9/10 10:51 下午
     * @param exception:
     * @return: com.example.study.basic.model.ResultModel
     */
    @ExceptionHandler(value = Exception.class)
    public ResultModel catchException(Exception exception) {
        LoggerUtil.error("未知异常",exception);
        String message = exception.toString();
        ResultModel resultModel = ResultModel.builder()
                .code(BasicCode.STANDARD_ERROR.code)
                .msg("未知异常")
                .data(message)
                .build();
        return resultModel;
    }

    /**
     * @description: 捕获自定义异常
     * @author: nannan
     * @date: 2020/9/10 10:51 下午
     * @param basicException:
     * @return: com.example.study.basic.model.ResultModel
     */
    @ExceptionHandler(value = BasicException.class)
    public ResultModel catchBasicException(BasicException basicException) {
        LoggerUtil.error(basicException.getMessage(),basicException);
        return ResultModel.builder()
                .code(basicException.getCode())
                .msg(basicException.getMsg())
                .build();
    }

    /**
     * @description: 异常转字符串
     * @author: nannan
     * @date: 2020/9/12 8:25 上午
     * @param throwable
     * @return: java.lang.String
     */
    private String exceptionToString(Throwable throwable) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        throwable.printStackTrace(pw);
        return sw.toString();
    }
}
